import 'dart:convert';

import 'package:ai_data_capture/bean/FlowBean.dart';
import 'package:ai_data_capture/util/JsonUtil.dart';
import 'package:ai_data_capture/util/toast_util.dart';
import 'package:ai_data_capture/widget/custom_textfield_widget.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

Future<String?> showEditDialog(c) async {
  var config = "$c".obs;
  String? res = await Get.dialog(PopScope(
    canPop: false,
    child: Center(
      child: Container(
        width: Get.width * 0.8,
        height: Get.height * 0.8,
        decoration: BoxDecoration(
            color: Colors.white, borderRadius: BorderRadius.circular(10)),
        child: Column(
          children: [
            Stack(
              children: [
                const SizedBox(
                  width: double.infinity,
                  height: 50,
                  child: Center(
                      child: Text(
                    "编辑配置",
                    style: TextStyle(fontWeight: FontWeight.bold),
                  )),
                ),
                Positioned(
                    right: 0,
                    top: 0,
                    bottom: 0,
                    child: InkWell(
                      onTap: () {
                        try {
                          config.value = JsonUtil.format(config.value);
                          showToast("格式化成功");
                        } catch (e) {
                          print(e);
                          showToast("格式化失败，请检查json");
                        }
                      },
                      child: const Padding(
                        padding: EdgeInsets.all(8.0),
                        child: Center(
                          child: Text(
                            "格式化",
                            style: TextStyle(fontWeight: FontWeight.bold),
                          ),
                        ),
                      ),
                    ))
              ],
            ),
            Expanded(
                child: Container(
                    decoration: BoxDecoration(color: Colors.grey.shade50),
                    height: 100,
                    margin: const EdgeInsets.symmetric(horizontal: 10),
                    child: Obx(() {
                      return CustomTextField(
                        value: config.value,
                        onChanged: (t) {
                          config.value = t;
                        },
                        style: const TextStyle(fontWeight: FontWeight.bold),
                      );
                    }))),
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: Row(mainAxisAlignment: MainAxisAlignment.end, children: [
                InkWell(
                  onTap: Get.back,
                  child: Container(
                    padding: const EdgeInsets.symmetric(
                        horizontal: 25, vertical: 10),
                    decoration: BoxDecoration(
                        color: Colors.grey.shade200,
                        borderRadius: BorderRadius.circular(5)),
                    child: const Text(
                      "取消",
                      style: TextStyle(
                          color: Colors.black, fontWeight: FontWeight.bold),
                    ),
                  ),
                ),
                const SizedBox(width: 10),
                InkWell(
                    onTap: () {
                      Get.back(result: jsonEncode(jsonDecode(config.value)));
                    },
                    child: Container(
                        padding: const EdgeInsets.symmetric(
                            horizontal: 25, vertical: 10),
                        decoration: BoxDecoration(
                            color: Colors.blue,
                            borderRadius: BorderRadius.circular(5)),
                        child: const Text("提交",
                            style: TextStyle(
                                color: Colors.white,
                                fontWeight: FontWeight.bold))))
              ]),
            )
          ],
        ),
      ),
    ),
  ));
  return res;
}

class AddFlowBean {
  final String description;
  final String step;

  AddFlowBean({required this.description, required this.step});
}

Future<AddFlowBean?> showAddFlowDialog(List<String> funcs,
    {FlowBean? flow}) async {
  var des = "".obs;
  RxList<String> flows = <String>[].obs;
  if (flow != null) {
    des.value = flow.description ?? "";
    flows.addAll(flow.step?.split(",") ?? []);
  }
  return await Get.dialog(PopScope(
    canPop: false,
    child: Center(
      child: Container(
        padding: const EdgeInsets.all(10),
        width: Get.width * 0.8,
        decoration: BoxDecoration(
            color: Colors.white, borderRadius: BorderRadius.circular(10)),
        child: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const SizedBox(
                  width: double.infinity,
                  height: 50,
                  child: Center(
                      child: Text("添加流程",
                          style: TextStyle(fontWeight: FontWeight.bold)))),
              Container(
                  margin: const EdgeInsets.symmetric(vertical: 10),
                  decoration: BoxDecoration(
                      color: Colors.grey.shade200,
                      borderRadius: BorderRadius.circular(10)),
                  child: Row(children: [
                    const Padding(
                        padding: EdgeInsets.all(10), child: Text("流程描述")),
                    Expanded(child: Obx(() {
                      return CustomTextField(
                          value: des.value,
                          onChanged: (t) {
                            des.value = t;
                          },
                          inputDecoration: const InputDecoration(
                              contentPadding: EdgeInsets.all(10),
                              isCollapsed: true,
                              isDense: true,
                              border: InputBorder.none));
                    }))
                  ])),
              const Text("选择流程"),
              GridView.builder(
                  physics: const NeverScrollableScrollPhysics(),
                  itemCount: funcs.length,
                  padding: EdgeInsets.zero,
                  shrinkWrap: true,
                  gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 4,
                      mainAxisSpacing: 5,
                      crossAxisSpacing: 5,
                      childAspectRatio: 1.6),
                  itemBuilder: (BuildContext context, int index) {
                    var b = funcs[index];
                    return InkWell(
                      onTap: () {
                        if (flows.where((m) => m == b).isEmpty) {
                          flows.add(b);
                        } else {
                          flows.remove(b);
                        }
                      },
                      child: Obx(() {
                        return Container(
                            margin: const EdgeInsets.all(2),
                            decoration: BoxDecoration(
                              color: flows.where((m) => m == b).isNotEmpty
                                  ? Colors.blue
                                  : Colors.grey.shade200,
                              borderRadius: BorderRadius.circular(5),
                            ),
                            child: Center(child: Obx(() {
                              return Text(
                                b,
                                style: TextStyle(
                                    color: flows.where((m) => m == b).isNotEmpty
                                        ? Colors.white
                                        : Colors.black),
                              );
                            })));
                      }),
                    );
                  }),
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: Row(mainAxisAlignment: MainAxisAlignment.end, children: [
                  InkWell(
                      onTap: Get.back,
                      child: Container(
                          padding: const EdgeInsets.symmetric(
                              horizontal: 25, vertical: 10),
                          decoration: BoxDecoration(
                              color: Colors.grey.shade200,
                              borderRadius: BorderRadius.circular(5)),
                          child: const Text("取消",
                              style: TextStyle(
                                  color: Colors.black,
                                  fontWeight: FontWeight.bold)))),
                  const SizedBox(width: 10),
                  InkWell(
                      onTap: () {
                        if (des.value.isEmpty) {
                          showToast("请输入描述");
                          return;
                        }
                        Get.back(
                            result: AddFlowBean(
                                description: des.value, step: flows.join(",")));
                      },
                      child: Container(
                          padding: const EdgeInsets.symmetric(
                              horizontal: 25, vertical: 10),
                          decoration: BoxDecoration(
                              color: Colors.blue,
                              borderRadius: BorderRadius.circular(5)),
                          child: const Text("提交",
                              style: TextStyle(
                                  color: Colors.white,
                                  fontWeight: FontWeight.bold))))
                ]),
              )
            ],
          ),
        ),
      ),
    ),
  ));
}
